package com.shi.yibanjia.controller;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shi.yibanjia.annotation.Auth;
import com.shi.yibanjia.annotation.MyLog;
import com.shi.yibanjia.common.Result;
import com.shi.yibanjia.entity.po.CarType;
import com.shi.yibanjia.entity.po.TransportFee;
import com.shi.yibanjia.enums.AuthCodeEnum;
import com.shi.yibanjia.enums.LogType;
import com.shi.yibanjia.service.CarTypeService;
import com.shi.yibanjia.service.TransportFeeService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/admin/transportFee")
public class TransportFeeController {
    @Resource
    private TransportFeeService transportFeeService;

    @Resource
    private CarTypeService carTypeService;

    @GetMapping
    @Auth(hasPerm = AuthCodeEnum.BIZ_TRANSPORT_FEE_DQL)
    @Cacheable(value = "yibanjia:transprotFee", key = "'list'")
    public Result getCarryFeeList() {
        return Result.ok(transportFeeService.list());
    }

    @MyLog(type = LogType.UPDATE)
    @PutMapping
    @Auth(hasPerm = AuthCodeEnum.BIZ_TRANSPORT_FEE_DML)
    @CacheEvict(value = {"yibanjia:transprotFee", "yibanjia:carryAndTransport"}, allEntries = true)
    public Result updateCarryFee(@RequestBody TransportFee transportFee) {
        transportFeeService.updateById(transportFee);
        return Result.ok();
    }

    @MyLog(type = LogType.DELETE)
    @DeleteMapping("/{id}")
    @Auth(hasPerm = AuthCodeEnum.BIZ_TRANSPORT_FEE_DML)
    @CacheEvict(value = {"yibanjia:transprotFee", "yibanjia:carryAndTransport"}, allEntries = true)
    public Result remove(@PathVariable("id") Long id) {
        transportFeeService.removeById(id);
        return Result.ok();
    }

    @MyLog(type = LogType.INSERT)
    @PostMapping
    @Auth(hasPerm = AuthCodeEnum.BIZ_TRANSPORT_FEE_DML)
    @CacheEvict(value = {"yibanjia:transprotFee", "yibanjia:carryAndTransport"}, allEntries = true)
    public Result add(@RequestBody TransportFee transportFee) {
        TransportFee transportFee1 = transportFeeService.getOne(new LambdaQueryWrapper<TransportFee>()
                .eq(TransportFee::getCarTypeName, transportFee.getCarTypeName()));
        if (ObjUtil.isNotEmpty(transportFee1)) {
            return Result.fail("该车型的收费标准已存在，请通过编辑修改~");
        }
        CarType one = carTypeService.getOne(new LambdaQueryWrapper<CarType>()
                .eq(CarType::getName, transportFee.getCarTypeName()));
        if (ObjUtil.isEmpty(one)) {
            return Result.fail("该车型名称不存在，请先添加车型~");
        }
        transportFee.setCarTypeId(one.getId());
        transportFeeService.save(transportFee);
        return Result.ok();
    }
}
